package com.wenwen.social.application.listeners;

import com.wenwen.social.application.event.MessageDelEvent;
import com.wenwen.social.domain.model.*;
import com.wenwen.social.domain.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;

@Component
public class MessageDelListener {
	@Autowired
	private UserService userService;
	@Autowired
	private PersonLineService personLineService;
	@Autowired
	private HomeLineService homeLineService;
	@Autowired
	private FollowService followService;
	@Autowired
	private FansService fansService;
	@Autowired
	private FollowLineService followLineService;
	/**
	 * 更新用户已发送信息数
	 * @param event
	 */
	@Async
	@EventListener
	public void updateMsgNum(MessageDelEvent event)
	{
		Long uid = event.getMessage().getUid();
		User user = userService.getUser(uid);
		if(user == null) return;
		Long messages = user.getMessages();
		if(messages != null){
			user.setMessages(messages-1);
			userService.updateUser(user);
		}
	}
	@Async
	@EventListener
	public void personLineDel(MessageDelEvent event)
	{
		Message message = event.getMessage();
		Long uid = message.getUid();
		Long id = message.getId();
		personLineService.del(uid,id);
	}
	@Async
	@EventListener
	public void homeLineDel(MessageDelEvent event)
	{
		Message message = event.getMessage();
		Long uid = message.getUid();
		Long id = message.getId();
		//更新主页时间线
		homeLineService.del(uid,id);
	}
	@Async
	@EventListener
	public void followLineDel(MessageDelEvent event)
	{
		Message message = event.getMessage();
		Long uid = message.getUid();
		Long id = message.getId();
		delMessageFromFollowLine(uid,id);
		followLineService.del(uid,id);
	}
	private void delMessageFromFollowLine(Long uid, Long msgId) {
		Fans fans = fansService.queryFans(uid, 1, -1);
		if(fans == null) return;
		Map<Long, Long> followMap = fans.getFansMap();
		if (followMap == null || followMap.isEmpty()) return;
		Set<Long> fansIds = followMap.keySet();
		followLineService.del(fansIds,msgId);
	}
}
